package com.lili.collection.core.context.impl;

import com.lili.collection.core.context.ExchangeStageContext;
import com.lili.collection.core.context.StageContext;
import com.lili.collection.core.runner.StageRunner;
import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 单值交换上下文
 *
 * @author lili
 * @date 2023/3/9 0:41
 */
public class BlockingQueueExchangeStageContext implements ExchangeStageContext {

    private Map<StageRunner.StageType, ArrayBlockingQueue<StageContext>> stageContextQueue;

    public BlockingQueueExchangeStageContext() {
        this.stageContextQueue = new HashMap<>();
        for (StageRunner.StageType stageType : StageRunner.StageType.values()) {
            this.stageContextQueue.put(stageType, new ArrayBlockingQueue<StageContext>(1));
        }
    }

    @SneakyThrows
    @Override
    public StageContext take(StageRunner.StageType stageType) {
        return stageContextQueue.get(stageType).take();
    }

    @SneakyThrows
    @Override
    public void put(StageRunner.StageType stageType, StageContext stageContext) {
        stageContextQueue.get(stageType).put(stageContext);
    }

    @Override
    public StageContext peek(StageRunner.StageType stageType) {
        return stageContextQueue.get(stageType).peek();
    }

    @Override
    public void clear() {
        this.stageContextQueue = null;
    }
}
